from datetime import datetime

from sqlalchemy import String, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.db.base import Base
# 导入角色模型和关联表
from app.models.role import Role, user_role
from app.models.tenant import Tenant


class User(Base):
    __tablename__ = "users"

    id: Mapped[str] = mapped_column(String(32), primary_key=True, index=True)
    email: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=True)
    login_name: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
    full_name: Mapped[str] = mapped_column(String(100), nullable=True)
    hashed_password: Mapped[str] = mapped_column(String(64), nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    is_superuser: Mapped[bool] = mapped_column(Boolean, default=False)
    tenant_id: Mapped[str] = mapped_column(String(32), ForeignKey("tenants.id"), nullable=True)
    created_user: Mapped[str] = mapped_column(String(32))
    created_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.utcnow)
    updated_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 添加与租户的关系
    # tenant: Mapped["Tenant"] = relationship("Tenant", lazy="selectin")

    # 添加与角色的多对多关系
    roles: Mapped[list["Role"]] = relationship(
        "Role",
        secondary=user_role,
        back_populates="users",
        lazy="selectin"
    )

    def __repr__(self):
        return f"<User(id='{self.id}', login_name='{self.login_name}', tenant_id='{self.tenant_id}')>"
